package RateService

import (
	RateModel "blog/app/models/rate_model"
	"blog/config"
	"blog/service"
	"blog/utils"
	"blog/utils/tools"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"io"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type Response struct {
	Head    Head     `json:"head"`
	Data    Data     `json:"data"`
	Records []Record `json:"records"`
}

type Head struct {
	Version    string `json:"version"`
	Provider   string `json:"provider"`
	ReqCode    string `json:"req_code"`
	RepCode    string `json:"rep_code"`
	RepMessage string `json:"rep_message"`
	Ts         int64  `json:"ts"`
	Producer   string `json:"producer"`
	Tstext     string `json:"tstext"`
}

type Data struct {
	Total       int      `json:"total"`
	StartDate   string   `json:"startDate"`
	PageTotal   int      `json:"pageTotal"`
	Searchlist  []string `json:"searchlist"`
	PageSize    int      `json:"pageSize"`
	EndDate     string   `json:"endDate"`
	FlagMessage string   `json:"flagMessage"`
	Head        []string `json:"head"`
	Currency    string   `json:"currency"`
	PageNum     int      `json:"pageNum"`
}

type Record struct {
	Date   string   `json:"date"`
	Values []string `json:"values"`
}

func RequestDay(c *gin.Context) {

	startDate := c.Query("startDate")
	endDate := c.Query("endDate")
	pageNum := c.Query("pageNum")
	pageSize := c.Query("pageSize")
	fmt.Println("原始请求参数", pageNum, pageSize)
	pageNumInt, _ := strconv.ParseInt(pageNum, 10, 64)
	pageSizeInt, _ := strconv.ParseInt(pageSize, 10, 64)
	DealDataByDatePage(startDate, endDate, pageNumInt, pageSizeInt)

	service.CommonCJsonReply(c, config.SUCCESS, "ok")
}

// DealDataByDatePage 基础根据开始日期和结束日期以及分页获取处理数据
func DealDataByDatePage(startDate, endDate string, pageNum, pageSize int64) {
	log.Println("开始获取数据写入mysql,开始日期" + startDate + "结束日期:" + endDate)
	hostUrl := viper.GetString("chinamoney.host")
	// https://iftp.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate=2024-12-01&endDate=2024-12-31&pageNum=3&pageSize=10
	url := fmt.Sprintf("%s/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate=%s&endDate=%s&pageNum=%d&pageSize=%d", hostUrl, startDate, endDate, pageNum, pageSize)

	// 发起GET请求获取数据
	resp, err := http.Get(url)
	if err != nil {
		log.Printf("请求失败: %v", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("读取响应失败: %v", err)
		return
	}

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		log.Printf("请求返回错误状态码: %d, 响应内容: %s", resp.StatusCode, string(body))
		return
	}

	// 打印响应内容
	log.Printf("响应数据: %s", string(body))
	var res Response

	err = json.Unmarshal(body, &res)
	if err != nil {
		fmt.Println(err)
	}

	// 处理表头
	fmt.Println("处理表头", res.Data.Head)
	for _, v := range res.Data.Head {
		fmt.Println(v)

	}

	for _, item := range res.Records {
		fmt.Println(item.Date)

	}

	// 获取当前时间
	now := time.Now()

	// 遍历每条记录
	for _, record := range res.Records {
		// 遍历每个汇率对
		for i, rate := range record.Values {
			if i >= len(res.Data.Head) {
				continue
			}

			// 拆分货币对
			currencies := strings.Split(res.Data.Head[i], "/")
			if len(currencies) != 2 {
				continue
			}
			rateTime, _ := tools.TryParseTime(record.Date)
			// 创建记录
			rateRecord := &RateModel.RateRecord{
				FromCode:    currencies[0],
				ToCode:      currencies[1],
				Rate:        rate,
				RateDate:    rateTime,
				RateTime:    now.Format("2006-01-02 15:04:05"),
				CreatedTime: now,
				UpdatedTime: now,
				CreatedBy:   "system",
				UpdatedBy:   "system",
			}

			// 保存到数据库
			err := utils.MySqlDB.Model(&RateModel.RateRecord{}).Create(&rateRecord)
			if err.Error != nil {
				fmt.Printf("Error creating item: %v\n", err)
				log.Printf("Error creating item: %v\n\n", err)
			}
		}
	}

}
